import React, { useState, useEffect } from 'react';
import EmergencyButton from './components/EmergencyButton';
import ContactDropdown from './components/ContactDropdown';
import NoteInput from './components/NoteInput';
import AlertModal from './components/AlertModal';
import AlertHistory from './components/AlertHistory';
import { getContacts, sendAlert } from './services/api';
import './styles/App.css';

const App = () => {
  const [contacts, setContacts] = useState([]);
  const [selectedContact, setSelectedContact] = useState('');
  const [note, setNote] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [modal, setModal] = useState({
    isVisible: false,
    type: 'success',
    message: ''
  });
  const [alertHistory, setAlertHistory] = useState([]);
  const [isHistoryVisible, setIsHistoryVisible] = useState(false);

  // 从后端获取紧急联系人
  useEffect(() => {
    const fetchContacts = async () => {
      try {
        const response = await getContacts();
        if (response.success) {
          setContacts(response.data);
        } else {
          console.error('获取联系人失败:', response.message);
        }
      } catch (error) {
        console.error('获取联系人异常:', error);
        // 使用模拟数据作为备选
        setContacts([
          { id: 1, name: '张伟', phone: '138****1234', relationship: '家人' },
          { id: 2, name: '李芳', phone: '139****5678', relationship: '朋友' },
          { id: 3, name: '王明', phone: '136****9012', relationship: '同事' }
        ]);
      }
    };

    fetchContacts();
  }, []);

  // 处理报警提交
  const handleEmergencyAlert = async () => {
    if (!selectedContact) {
      setModal({
        isVisible: true,
        type: 'error',
        message: '请先选择紧急联系人！'
      });
      return;
    }

    setIsLoading(true);
    
    try {
      // 调用报警API
      const response = await sendAlert({
        contactId: selectedContact,
        note: note
      });
      
      if (response.success) {
        // 添加到报警历史
        const newAlert = {
          id: Date.now(),
          contact: contacts.find(c => c.id == selectedContact),
          note: note,
          timestamp: new Date().toLocaleString(),
          status: '成功'
        };
        
        setAlertHistory(prev => [newAlert, ...prev]);
        
        setModal({
          isVisible: true,
          type: 'success',
          message: response.message || '报警成功！紧急联系人已收到通知。'
        });
        
        // 重置表单
        setSelectedContact('');
        setNote('');
      } else {
        setModal({
          isVisible: true,
          type: 'error',
          message: response.message || '报警失败，请稍后重试。'
        });
      }
    } catch (error) {
      console.error('报警请求失败:', error);
      setModal({
        isVisible: true,
        type: 'error',
        message: '网络错误，请检查连接后重试。'
      });
    } finally {
      setIsLoading(false);
    }
  };

  const closeModal = () => {
    setModal({
      ...modal,
      isVisible: false
    });
  };

  return (
    <div className="app">
      <div className="app-container">
        <header className="app-header">
          <div className="header-content">
            <h1>紧急求助系统</h1>
            <p>在紧急情况下，通过此系统快速向您的紧急联系人求助</p>
          </div>
          <div className="header-actions">
            <button 
              className="history-toggle"
              onClick={() => setIsHistoryVisible(!isHistoryVisible)}
            >
              {isHistoryVisible ? '返回报警' : '查看记录'}
            </button>
          </div>
        </header>

        <main className="app-main">
          {!isHistoryVisible ? (
            <div className="alert-interface">
              <div className="alert-card">
                <div className="card-header">
                  <h2>紧急报警</h2>
                  <div className="status-indicator">
                    <div className="status-dot active"></div>
                    <span>系统在线</span>
                  </div>
                </div>
                
                <ContactDropdown
                  contacts={contacts}
                  selectedContact={selectedContact}
                  onContactChange={setSelectedContact}
                />
                
                <NoteInput
                  note={note}
                  onNoteChange={setNote}
                />
                
                <EmergencyButton
                  onClick={handleEmergencyAlert}
                  isLoading={isLoading}
                />
              </div>

              <div className="quick-tips">
                <h3>紧急情况提示</h3>
                <ul>
                  <li>尽量保持冷静，清晰描述您的位置和情况</li>
                  <li>如果可能，开启手机定位功能</li>
                  <li>在安全的情况下保持通话</li>
                  <li>报警后尽量停留在安全位置等待救援</li>
                </ul>
              </div>
            </div>
          ) : (
            <AlertHistory 
              alerts={alertHistory}
              onBack={() => setIsHistoryVisible(false)}
            />
          )}
        </main>

        <AlertModal
          isVisible={modal.isVisible}
          type={modal.type}
          message={modal.message}
          onClose={closeModal}
        />
      </div>
    </div>
  );
};

export default App;